package cn.yuanqiao.web.controller.archive.statistics;

import java.io.File;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import cn.yuanqiao.common.exception.ServiceException;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.yuanqiao.common.annotation.Log;
import cn.yuanqiao.common.enums.BusinessType;

import cn.yuanqiao.archive.statistics.domain.YearReport;
import cn.yuanqiao.archive.statistics.service.IYearReportService;
import cn.yuanqiao.common.web.controller.BaseController;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.utils.poi.ExcelUtil;
import cn.yuanqiao.common.web.page.TableDataInfo;

/**
 * 年报统计Controller
 * 
 * @author xy
 * @date 2023-07-28
 */
@RestController
@RequestMapping("/archive/yearReport")
public class YearReportController extends BaseController {
    @Autowired
    private IYearReportService yearReportService;

    /**
     * 查询年报统计列表
     */
/*
    @RequiresPermissions("archive:yearReport:list")
*/
    @GetMapping("/list")
    public TableDataInfo list(YearReport yearReport) {
        startPage();
        List<YearReport> list = yearReportService.selectYearReportList(yearReport);
        return getDataTable(list);
    }

    /**
     * 导出年报统计列表
     */
/*
    @RequiresPermissions("archive:yearReport:export")
*/
    @Log(title = "年报统计", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
//    @RequiresPermissions("archive:statistics:annualReport:export")
    public void export(HttpServletResponse response, YearReport yearReport) throws IOException {
        Resource resource = null;
        if (yearReport.getType().equals("0")) {
            resource = new ClassPathResource("yearReport/yearReport.xlsx");

        } else {
            resource = new ClassPathResource("yearReport/archives.xlsx");
        }
        InputStream inputStream = resource.getInputStream();
        try {
            Map map = new HashMap();
            com.alibaba.fastjson.JSONArray jsonArr = JSONArray.parseArray(yearReport.getContents());
            for (int i = 0; i < jsonArr.size(); i++) {
                JSONObject jsonObject = jsonArr.getJSONObject(i);
                String name = jsonObject.getString("name");
                String value = jsonObject.getString("value");
                map.put(name, value);
            }

            List list = new ArrayList();
            list.add(map);


            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("年报统计表", "UTF-8");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment;filename=" + yearReport.getYear() + "年年报统计.xlsx");
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).autoTrim(false).withTemplate(inputStream).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            excelWriter.fill(list, writeSheet);
            excelWriter.finish();
            inputStream.close();
            // util.exportExcel(response, list, "年报统计数据");
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            throw new ServiceException("导出错误");
        } finally {
            inputStream.close();
        }
    }

    /**
     * 获取年报统计详细信息
     */
/*
    @RequiresPermissions("archive:yearReport:query")
*/
    @GetMapping(value = "/{year}/{type}")
    public AjaxResult getInfo(@PathVariable("year") String year, @PathVariable("type") String type) {
        return success(yearReportService.selectYearReportByYear(year, type));
    }

    /**
     * 新增年报统计
     */
/*
    @RequiresPermissions("archive:yearReport:add")
*/
//    @RequiresPermissions("archive:statistics:annualReport:add")
    @Log(title = "年报统计", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody YearReport yearReport) {
        return toAjax(yearReportService.insertYearReport(yearReport));
    }

    /**
     * 修改年报统计
     */
/*
    @RequiresPermissions("archive:yearReport:edit")
*/
    @Log(title = "年报统计", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody YearReport yearReport) {
        return toAjax(yearReportService.updateYearReport(yearReport));
    }

    /**
     * 删除年报统计
     */
/*
    @RequiresPermissions("archive:yearReport:remove")
*/
    @Log(title = "年报统计", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(yearReportService.deleteYearReportByIds(ids));
    }

    @GetMapping("/statistics/{year}")
    public AjaxResult statistics(@PathVariable("year") String year) {

        return success(yearReportService.statistics(year));

    }

    @GetMapping("/archivesStatistics/{year}")
    public AjaxResult archivesStatistics(@PathVariable("year") String year) {

        return success(yearReportService.archivesStatistics(year));

    }
}
